package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.protobuf.DescriptorProtos;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author zm
 * @since 2022-06-28
 */
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    @Lazy    //懒加载
    private IAuditService auditService;

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            //WmNews::getPublishTime 大于等于  getBeginPubDate
            //WmNews::getPublishTime 小于等于  getEndPubDate
            queryWrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
            queryWrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        }

        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        queryWrapper.eq(WmNews::getUserId,user.getUserId());
        //隐藏条件：登录人
        queryWrapper.orderByDesc(WmNews::getPublishTime);

        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());

        Page<WmNews> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        User user = UserThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //先判断是否有id，如果有就是修改，没有就是新增
        if (wmNewsDto.getId()!=null){
            //删除已关联素材的关系
            deleteRelation(wmNewsDto.getId());
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setStatus(wmNewsDto.getStatus());// TODO   提交为1  草稿为0
        //wmNews.setReason(); //审核失败的原因 ，先不处理
        //wmNews.setArticleId(); // app文章的id，等审核通过后 远程调用article微服务生成一个app文章 返回app文章的id ，先不处理
        List<ImageDto> coverImageList = wmNewsDto.getImages();

        wmNews.setImages(JSON.toJSONString(coverImageList)); // TODO
        wmNews.setEnable(true);

        //从文章内容中获取所有的图片，构建到一个List集合中
        List<ImageDto> contentImagesList = getImageListFromContent(wmNewsDto.getContent());
        if(wmNewsDto.getType()==-1){ //封面图片是要自动从文章内容中获取
            int size = contentImagesList.size();
            //没有图片
            if(size ==0){
                wmNews.setType(0);
                coverImageList  = contentImagesList;
            }else if(size>0&&size<3){
                //文章内容有少于3个图片
                wmNews.setType(1);
                coverImageList = contentImagesList.subList(0, 1);
            }else  if(size>=3){
                //文章内容多于或等于3个图片
                wmNews.setType(3);
                coverImageList = contentImagesList.subList(0, 3);
            }
            wmNews.setImages(JSON.toJSONString(coverImageList));
        }

        this.saveOrUpdate(wmNews); //如果有id就是update，如果没有ID就是save

        //wmNews.setStatus(dto.getStatus());// TODO   提交为1  草稿为0
        //判断是否为草稿
        if(wmNewsDto.getStatus()==1){
            //关联内容中的图片与素材的关系
            saveRelation(contentImagesList,wmNews.getId(),0);
            //关联封面图片与素材的关系
            saveRelation(coverImageList,wmNews.getId(),1);

            //调用自媒体文章审核的方法
            auditService.audit(wmNews); //这个方法比较耗时的  1、阿里云文本审核 2、阿里云图片审核 3、feign保存app文章
            //因为上边这个方法比较消耗时间，所以可以采用异步的方案：
            //异步有两种做法：1、借助MQ  2、使用多线程（本次使用）
        }

        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //1、先判断是否有文章id
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、再判断根据id是否能查询出对象
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3、判断这个自媒体文章是当前登录人发布的吗
        if (user.getUserId() != wmNews.getUserId()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //4、判断文章是否为发布状态
        if (wmNews.getStatus()!=9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_UP_DOWN);
        }

        wmNews.setEnable(dto.getEnable()==1?true:false);   //true 1 上架 false0 下架
        this.updateById(wmNews);

        //向kafka中发送消息
        Map map = new HashMap<>();
        map.put("articled",wmNews.getArticleId());
        map.put("enable",dto.getEnable()==1?true:false);

        kafkaTemplate.send(upDownTopic,JSON.toJSONString(map));
        log.info("上下架后向kafka中放入数据");
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Value("${topic.upDownTopic}")
    private String upDownTopic;


    private void saveRelation(List<ImageDto> contentImagesList, Integer newsId, int type) {
        int ord = 0;
        for (ImageDto imageDto : contentImagesList) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(ord);
            ord++;
            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }

    private List<ImageDto> getImageListFromContent(String content) {
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
        List<ImageDto> imageDtoList = new ArrayList<>();
        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;
    private void deleteRelation(Integer newsId) {
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,newsId);
        wmNewsMaterialService.remove(queryWrapper);
    }

}
